package grailsforum

class PostsController {

    static allowedMethods = [

            addPost: 'POST',
            editPost: 'POST'
    ]

    def addPost(){

        Thread thread = Thread.get(params.thread)

        Post post = new Post()
        post.thread = thread
        post.text = params.text
        post.position = thread.posts.size()
        post.date = new Date()
        post.user = User.get(params.user)
        post.save()

        render "ok"
    }

    def editPost(){

        Post post = Post.get(params.post)
        post.text = params.text
        post.save()

        render "ok"
    }

    def deletePost(){

        Post post = Post.get(params.post)
        Thread thread = Thread.get(params.thread)

        thread.posts.each {

            if(it.position > post.position){

                it.position--
//                it.save()
            }
        }

        thread.posts.remove(post);
        post.delete()
        thread.save()

        render "ok"
    }
}
